package com.demo.juc.base;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @Author: shubin_yao
 * @Date: 2022/04/30/9:51
 * @Description:
 *
 * Callable 使用细节：
 *
 * 1、FutureTask 是连接 Callable和Runnable 接口的纽带
 * 2、使用细节：
 *  2.1 FutureTask.get() 放在最后 ，避免阻塞
 *  2.2 同一个 FutureTask 在多个线程 调用时只执行一次，java 自带缓存
 */
public class T3CallableThread implements Callable<String> {
    @Override
    public String call() throws Exception {
        //to do sth
        TimeUnit.SECONDS.sleep(3);
        System.out.println("come in here !");
        return "hello";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask<>(new T3CallableThread());
        new Thread(futureTask,"A").start();  //futureTask  extends Runnable
        //new Thread(futureTask,"B").start();  // 不会显示 come in here

       // System.out.println(futureTask.get());     //放在这个位置可能阻塞
        System.out.println(Thread.currentThread() + "------");

        System.out.println(futureTask.get());     //一般放在这里

    }
}
